package org.codeforseattle.teacherdepot.http.servlet;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

import static com.google.appengine.api.users.UserServiceFactory.getUserService;
import static org.codeforseattle.teacherdepot.util.HttpIO.outJson;

/**
 * @author hrovira
 */
public class WhoamiServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(WhoamiServlet.class.getName());

    private final UserService userService = getUserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = userService.getCurrentUser();

        try {
            JSONObject json = new JSONObject();
            if (user != null && userService.isUserLoggedIn()) {
                log.info("logged in");

                json.put("email", user.getEmail());
                json.put("isAdmin", userService.isUserAdmin());
                json.put("logoutUrl", userService.createLogoutURL("/"));
            } else {
                log.info("not logged in");
                json.put("loginUrl", userService.createLoginURL("/"));
            }

            outJson(resp, json);
        } catch (JSONException e) {
            throw new ServletException(e);
        }
    }
}
